import { $Http } from '@/config/service/http';
import SparkMD5 from 'spark-md5'

const S_KEY= '123456789@sdw';
const codes = {
  'pdm': 1,
  'mes': 2,
  'aps': 3,
  'wms': 4,
  'dms': 5,
  'qms': 6,
  'eam': 7,
  'scada': 8,
  'dt': 9,
}
let systemName = import.meta.env.VITE_PUBLIC_PATH.split('/').find(res=>res.includes('-')).split('-')[0];

//加密DM5
const get_filemd5sum = (file:any,fn:any = null)=> {
  let fileReader:any = new FileReader();
  fileReader.readAsArrayBuffer(file);
  fileReader.onload = function(e:any){
    let buffer = e.target.result  
    let spark:any = new SparkMD5.ArrayBuffer(); 
    spark.append(buffer); 
    let str:string = spark.end();
    str = str.toLocaleUpperCase() ;  //转大写
    if( fn ){
      fn(str)
    }else{
      return str
    }
  }
}
//开启分片上传
/**
 * 
 * @param file //文件流
 * @param directoryId //文件夹ID
 * @param fileName  //文件名称
 * @param fileSize   //文件大小
 * @param hashCode   //整个文件的hash值
 * @param partNumber   //分片数量要大于1
 * @param storeUrl   //存储路径
 * 
 */
export const startPartUpload = (info:any ={},loading:any,fn:any =null,errFn=null)=>{
  if (!info?.file) {
    fn?.(null);
    return;
  }
  let file = info.file;
  let size = file.size;
  let shardSize = 5 * 1025 * 1025;               //以5 MB为一个分片,每个分片的大小
  let partNumber = Math.ceil(size / shardSize);  //总片数
  loading.value = true;
  get_filemd5sum(file,(fileId)=>{
    loading.value = false;
    let fileParams = {
      fileName: file.name,
      fileSize: file.size,
      partNumber,
      fileId,
      hashCode: '111',
      subsystem: codes[systemName]
    }
    console.log('总片数',file.name,fileId,partNumber);
    $Http.api('dmsfile/resourceFileInfo/startMd5PartUpload', fileParams, 'post','','', {} , 120000).then((res)=>{
      if( res && res.success ){
        let array = [];
        if(res.data.filePartUploadInfoList && res.data.filePartUploadInfoList.length){ //重新上传
          res.data.filePartUploadInfoList.forEach((item)=>{
            let start = item.index * shardSize;
            let end =  ((partNumber -1) === item.index ? size : start + shardSize) - 1;
            let packet = file.slice(start, end+1);  //将文件进行切片
            let form:any = new FormData();
            form.append("file", packet);
            form.append("fileId", fileId);
            form.append("partIndex", item.index);
            array = array.concat(form);
          })
        }else{
          for (let index = 0; index < partNumber; index++) {
            let start = index * shardSize;
            let end =  ((partNumber -1) === index ?size : start + shardSize) - 1;
            let packet = file.slice(start, end+1);  //将文件进行切片
            let form:any = new FormData();
            form.append("file", packet);
            form.append("fileId", fileId);
            form.append("partIndex", index);
            array = array.concat(form);
          }
        }
        startMap(array,uploadPartFile, 10, info, fileParams, file, fn,errFn)
        // pMap(array,uploadPartFile, 10,info).then(function(data:any) {
        //   console.log('看下请求参数',data,array);
        //   let obj = data.find(obj=>obj.data && obj.data.allFinish)
        //   if(obj){
        //     endPartUpload(fileParams,fn)
        //   }else{
        //     let againFile = data.filter(again=>!again.data.finish)[0].filePartUploadInfoList;
        //     let errArrIndex:any = againFile.filter(res=>res.filter(again=>!again.data.finish)).map(res=>res.index);
        //     let errArr = array.filter((res,index)=>errArrIndex.includes[index]);
        //     console.log('错误信息',errArr);
        //   }
        //   // all done here
        // }, function(err) {
        //   console.log('报错了',err);
        //   startPartUpload(file ={},fn =null)
        //     // error here
        // });
      }else {
        fn?.(null);
      }
    }).catch((err)=>{
      console.log('接口崩了',err);
      if( errFn ){
        errFn(info)
      }
    })
  })
}

function startMap (array,uploadPartFile, size, info, fileParams, file, fn,errFn){
  let partNumber = array.length;
  pMap(array,uploadPartFile, size,info).then(function(data:any) {
    console.log('看下请求参数',data);
    let obj = data.find(obj=>obj.data && obj.data.allFinish)
    if(obj){
      endPartUpload(fileParams,fn,info,errFn)
    }else if(partNumber === data.length){
      let againFile = data.filter(again=>!again.data?.finish)[0].filePartUploadInfoList;
      let errArrIndex:any = againFile.filter(res=>res.filter(again=>!again.data.finish)).map(res=>res.index);
      let errArr = array.filter((res,index)=>errArrIndex.includes[index]);
      startMap(errArr, uploadPartFile, size, info, fileParams, file, fn,errFn)
    }
    // all done here
  }, function(err) {
    console.log('报错了',err);
    fn?.(null)
    startPartUpload(file ={},fn =null)
      // error here
  });
}

function pMap(array,fn, limit,info) {
  return new Promise(function(resolve, reject) {
      var index = 0, cnt = 0, stop = false, results = new Array(array.length),repeat =1;
      function run() {
          while (!stop && index < ((repeat * limit) < array.length ? repeat * limit : array.length )  && cnt < limit) {
            console.log('总长度',((repeat * limit) < array.length ? repeat * limit : array.length), array.length);
              (function(i) {
                  ++cnt;
                  ++index;
                  fn(array[i]).then(function(data) {
                    info.onProgress({  percent: Math.round((index / array.length) * 100).toFixed(2) }, info.file);
                      results[i] = data;
                      --cnt;
                      if (cnt === 0 && index === array.length) {
                          resolve(results);
                      } else if( cnt === 0 ){
                        ++repeat;
                        run();
                      }else{
                          run();
                      }
                  }, function(err) {
                    console.log('错误提示',err);
                      stop = true;
                      --cnt;
                      reject(err);
                  });
              })(index);
          }
      }
      run();
  });
} 

//上传一个文件块 Form表单上传
/**
 * 
 * @param file
 * @param fileId
 * @param partIndex
 * 
 */
export const uploadPartFile = (params:any ={})=>{
  return $Http.api('dmsfile/resourceFileInfo/uploadMd5PartFile', params, 'post','','',{ 'Content-Type': 'multipart/form-data' },60000)
}

//分块上传结束
/**
 * 
 * @param id
 * 
 */
 export const endPartUpload = (params:any ={},fn:any=null,info=null,errFn=null)=>{
  $Http.api('dmsfile/resourceFileInfo/endMd5PartUpload', params, 'post','','',{}, 60000).then((res)=>{
    if( res && res.success ){
      if( fn ){
        fn(res.data)
      }
    }
  }).catch((err)=>{
    console.log('接口崩了',err);
    if( errFn ){
      errFn(info)
    }
  })
}